package com.zztl.infiniteBand.ui.fragment


import android.content.Intent
import android.view.View
import butterknife.OnClick
import com.andview.refreshview.XRefreshView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.clj.fastble.BleManager

import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpFragment
import com.zztl.infiniteBand.eventbus.*
import com.zztl.infiniteBand.model.FirmwareVersionBean
import com.zztl.infiniteBand.model.PersonInfoBean
import com.zztl.infiniteBand.model.UserAssetsBean
import com.zztl.infiniteBand.net.requestBean.FirmwareVersionRequest
import com.zztl.infiniteBand.presenter.MinePresenter
import com.zztl.infiniteBand.storage.Constans
import com.zztl.infiniteBand.ui.activity.*
import com.zztl.infiniteBand.ui.view.CommonItemView
import com.zztl.infiniteBand.ui.view.mvpview.MineView
import com.zztl.infiniteBand.util.*
import kotlinx.android.synthetic.main.fragment_mine_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @desc
 * @auth ${user}
 * @time 2018/9/13  16:05
 */
class MineFragment : BaseMvpFragment<MineView, MinePresenter>(), MineView {


    lateinit var mMinePresenter: MinePresenter
    private var isFirst = true
    private var mUserAssetsBean: UserAssetsBean? = null
    private var mAvailableAmount: Double = 0.toDouble()
    private var mFreezingAmount: Double = 0.toDouble()
    private var mTotalAmount: Double = 0.toDouble()
    private var mAuditState: String? = null
    private var mNickname: String? = null
    private var version: String? = null
    private var downUrl: String? = null
    private var hasUpgrade: Boolean = false

    override fun createPresenter(): MinePresenter {
        mMinePresenter = MinePresenter()
        return mMinePresenter
    }


    override fun setLayoutId(): Int = R.layout.fragment_mine_layout


    override fun initData() {
        EventBus.getDefault().register(this)
        xrefreshview?.let {
            it.setPinnedTime(800)
            it.setAutoLoadMore(false)
            it.pullLoadEnable = false
            it.setXRefreshViewListener(object : XRefreshView.SimpleXRefreshListener() {
                override fun onRefresh(isPullDown: Boolean) {
                    isFirst = true
                    mMinePresenter.getUserAssets(activity!!)

                }

                override fun onLoadMore(isSilence: Boolean) {

                }
            })
        }

        item_authentication.setLeftImg(R.mipmap.smrz_wode)
        item_authentication.setRightTextColor(resources.getColor(R.color.color_8993A4))

        item_find_watch.setLeftImg(R.mipmap.zhaoshebei_wod)
        item_message.setLeftImg(R.mipmap.xiaoxi_wod)
        item_authentication.setItemRightClickListener(object : CommonItemView.OnItemRightClickListener {
            override fun onClickItemRight(viewID: Int) {
                goToCertification()
            }
        })

        mMinePresenter.getUserAssets(activity!!)


        mMinePresenter.getFirmwareVersion(FirmwareVersionRequest("hhh"), activity!!)


    }


    @OnClick(R.id.item_authentication, R.id.item_find_watch, R.id.item_setting, R.id.btn_recharge, R.id.btn_mention, R.id.ll_user_info, R.id.btn_record, R.id.item_message)
    fun click(view: View) {
        when (view.id) {
            R.id.item_authentication -> goToCertification()
            R.id.item_find_watch -> {
                BleManager.getInstance().isConnected.let {
                    if (it) {
                        BleManager.getInstance().dataComonent.lostReminder { isReminder ->
                            if (isReminder) {
                                activity!!.toast(getString(R.string.查找设备中))
                            }
                        }
                    } else {
                        activity?.toast(getString(R.string.未连接设备))
                    }
                }
            }
            R.id.item_setting -> showActivity(Intent(activity, SettingActivity::class.java).apply {
                putExtra("upgrade", hasUpgrade)
                putExtra("downUrl", downUrl)
            })
            R.id.item_message -> showActivity(MessageCenterActivity::class.java)
            R.id.btn_recharge -> showActivity(RechargeActivity::class.java)   //充值
            R.id.btn_mention -> {  //提币
                if (null != mAuditState && "2" == mAuditState) {
                    val intent2 = Intent(activity, MentionActivity::class.java)
                    intent2.putExtra(Constans.USEABLEASSETS, DataFormatUtil.converTxtPoint4(mAvailableAmount))
                    activity!!.startActivity(intent2)
                } else {
                    toast(getString(R.string.尚未实名认证))
                }
            }
            R.id.ll_user_info -> showActivity(PersonInfoActivity::class.java)
            R.id.btn_record -> showActivity(RecordActivity::class.java)
        }

    }

    private fun goToCertification() {
        if (null != mAuditState) {
            if (mAuditState == "0") {
                activity!!.startActivity(Intent(activity, CertificationActivity::class.java))
            } else if ("1" == mAuditState) {
                toast(getString(R.string.审核中))
            } else if ("2" == mAuditState || "3" == mAuditState) {
                activity!!.startActivity(Intent(activity, AuditSuccessOrFailActivity::class.java))
            }
        } else {
            toast(getString(R.string.请检查网络))
        }
    }

    override fun getAssetsSuccess(userAssetsBean: UserAssetsBean) {
        mUserAssetsBean = userAssetsBean
        if (isFirst) {
            mMinePresenter.getUserInfo(activity!!)
        } else {
            setUserAssets(userAssetsBean)
        }
    }

    private fun setUserAssets(userAssetsBean: UserAssetsBean) {
        mAvailableAmount = userAssetsBean.data!!.availableAmount
        tv_useable_assets.text = DataFormatUtil.converTxtPoint4(mAvailableAmount)
        mFreezingAmount = userAssetsBean.data!!.freezingAmount
        tv_freeze_assets.text = DataFormatUtil.converTxtPoint4(mFreezingAmount)
        mTotalAmount = userAssetsBean.data!!.totalAmount
        tv_assets.text = DataFormatUtil.converTxtPoint4(mTotalAmount)
    }

    override fun getInfoSuccess(infoBean: PersonInfoBean) {
        xrefreshview.stopRefresh()
        if (null != mUserAssetsBean && isFirst) {
            setUserAssets(mUserAssetsBean!!)
            isFirst = false
        }
        infoBean.data!!.imageUrl?.let {
            if (it.isNotEmpty()) {
                setHeaderImg(it)
            }
        }

        infoBean.data!!.nickname?.let {
            mNickname = if (it.isEmpty()) (if (infoBean.data?.realName!!.isEmpty()) infoBean.data?.email else (infoBean.data?.realName)) else it
            tv_user_name.text = mNickname
        }


        mAuditState = infoBean.data!!.auditState
        when (mAuditState) {
            "0" -> {
                item_authentication.setRightImg2Visible(true)
                item_authentication.rightTextStr = UiUtils.getString(R.string.去认证)
            }
            "1" -> {
                item_authentication.setRightImg2Visible(false)
                item_authentication.rightTextStr = UiUtils.getString(R.string.审核中)
            }
            "2" -> {
                item_authentication.setRightImg2Visible(true)
                item_authentication.rightTextStr = UiUtils.getString(R.string.认证成功)
            }
            "3" -> {
                item_authentication.setRightImg2Visible(true)
                item_authentication.rightTextStr = UiUtils.getString(R.string.认证失败)
            }
        }
    }


    private fun setHeaderImg(imgUrl: String) {
        Glide.with(this)
                .load(imgUrl)
                .apply(RequestOptions().placeholder(R.mipmap.ic_defaultphoto).transform(GlideCircleTransform(context!!)))
                .into(iv_user_icon)
    }

    /**
     * 网络请求失败的回调
     */
    override fun fail() {
        xrefreshview.stopRefresh()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(messageEvent: PayoutSuccessEvent) {
        val money = messageEvent.money
        val state = messageEvent.state
        mAvailableAmount -= java.lang.Double.valueOf(money)!!
        tv_useable_assets.text = DataFormatUtil.converTxtPoint4(mAvailableAmount)


        if ("0" != state) {
            mFreezingAmount += java.lang.Double.valueOf(money)!!
            tv_freeze_assets.text = DataFormatUtil.converTxtPoint4(mFreezingAmount)
        } else {
            mTotalAmount -= java.lang.Double.valueOf(money)!!
            tv_assets.text = DataFormatUtil.converTxtPoint4(mTotalAmount)
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(messageEvent: RefreshAssetsEvent) {
        if (!isFirst) {
            mMinePresenter.getUserAssets2(activity!!)
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(messageEvent: UpdateHeaderEvent) {
        val url = messageEvent.imgUrl
        setHeaderImg(url)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(messageEvent: AuditSuccessEvent) {
        mAuditState = "1"
        item_authentication.rightTextStr = getString(R.string.审核中)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(messageEvent: ChangeNickNameEvent) {
        val nickName = messageEvent.nickName
        tv_user_name.text = nickName
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(event: FirmwareUpdateEvent) {
        hasUpgrade = false
        iv_update.visibility = View.GONE
    }


    /**
     * 获取固件版本的回调
     */
    override fun getVersion(bean: FirmwareVersionBean) {
        version = bean.data?.version
        downUrl = bean.data?.url

    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)

        super.onDestroy()
    }


}
